package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String getPayUrl(Long orderId, Long total, String desc) {
        // 6个请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", desc);
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", total.toString());

        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getTradeType());

        try {
            // 下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 验证签名
            isSignatureValid(resp);

            // 获取支付链接
            String url = resp.get("code_url");
            if (StringUtils.isEmpty(url)) {
                // 获取链接失败
                throw new RuntimeException("支付链接为空!");
            }
            // 返回
            return url;
        } catch (Exception e) {
            log.error("微信统一下单失败，原因：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void isSignatureValid(Map<String, String> resp){
        boolean isValid = false;
        try {
            isValid = WXPayUtil.isSignatureValid(resp, payConfig.getKey(),
                    WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!isValid){
            // 签名有误，抛出异常
            throw new RuntimeException("签名有误！滚，再搞我就报警了！");
        }
    }

    /**
     * TODO 主动查询订单状态
     * @param orderId
     * @return
     */
    public Integer queryOrderState(Long orderId){
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", orderId.toString());
        try {
            Map<String, String> result = wxPay.orderQuery(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
